﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace Common.Utilities.OpenXml
{
	/// <summary>
	/// Provides a common base class for other classes that simplify access to commonly used package parts.
	/// </summary>
	public abstract class PackagePartBase
	{
		private readonly PackageHelper m_package;
		private readonly Uri m_uri;
		private XmlDocument m_xml;

		/// <summary>
		/// Allows creation by a derived class.  Stores the package and uri into internal fields.
		/// </summary>
		/// <param name="package">The package this part resides in.</param>
		/// <param name="uri">The uri of the part within the package.</param>
		protected PackagePartBase(PackageHelper package, Uri uri)
		{
			m_package = package;
			m_uri = uri;
		}

		/// <summary>
		/// Returns the Uri of the part.
		/// </summary>
		public Uri Uri
		{
			get { return m_uri; }
		}

		/// <summary>
		/// Returns the part's package to derived classes.
		/// </summary>
		protected PackageHelper Package
		{
			get { return m_package; }
		}

		/// <summary>
		/// Retrieves the Xml data from the package part when needed.
		/// </summary>
		protected XmlDocument PackageData
		{
			get
			{
				if (m_xml == null)
					m_xml = m_package.GetWritablePart(m_uri);
				return m_xml;
			}
		}

		/// <summary>
		/// Saves any changes made to the package part Xml.
		/// </summary>
		public void Flush()
		{
			if (m_xml != null)
			{
				m_package.SavePart(m_uri, m_xml);
				m_xml = null;
			}
		}
	}
}
